package org.opens.util;

import cn.hutool.core.io.IoUtil;
import com.jcraft.jsch.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;

public class SSHUtil {

    /**
     * 上传文件到服务器
     * @param host 服务器ip
     * @param username 用户名
     * @param password 密码
     * @param port ssh端口
     * @param outPath 输出路径
     * @param file 待上传文件
     */
    public static void uploadFile(String host, String username, String password, Integer port, String outPath, File file) {
        JSch jsch = new JSch();
        Session session = null;
        ChannelSftp channelSftp = null;
        InputStream inputStream = null;
        try {
            session = jsch.getSession(username, host, port);
            session.setPassword(password);
            Properties config = new Properties();
            //在代码里需要跳过检测。否则会报错找不到主机
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.setTimeout(30000);
            session.connect();
            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();
            channelSftp.cd(outPath);
            try {
                channelSftp.get(outPath + "/" + file.getName());
                channelSftp.rename(file.getName(), file.getName() + "-beifen");
            } catch (SftpException e) {

            }
            inputStream = new FileInputStream(file);
            channelSftp.put(inputStream, file.getName());
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(inputStream);
            if (channelSftp != null) {
                channelSftp.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }

}
